//
//  MIDIMyFocusController.m
//  迷笛
//
//  Created by . on 2018/9/13.
//  Copyright © 2018年 🍃🌺🌺🍃. All rights reserved.
//

#import "MIDIMyFocusController.h"
#import "MIDIMyfoucusCell.h"
#import "MIDIfoucusmodel.h"


@interface MIDIMyFocusController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * MyFocustable;
@property(nonatomic,strong)NSMutableArray * focusArr;
@property(nonatomic,copy)NSString * focusapi;
@property(nonatomic,copy)NSString * apptoken;

@property(nonatomic,copy)NSString * followapi;



@end

@implementation MIDIMyFocusController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(Block:)];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    [self.navigationItem.leftBarButtonItem setImage:[[UIImage imageNamed:@"后退"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    _apptoken = [user objectForKey:@"APPToken"];



    [self HomeUI];
}
-(void)focusrequest
{
    self.focusapi = [NSString stringWithFormat:@"%@users/getFollow?token=%@",MIDIApiRoot,_apptoken];
    
    [EdHttp get:self.focusapi params:nil progress:^(id downloadProgress)
    {
        
    }
        success:^(id responseObject)
     {
         NSLog(@"我的关注%@",responseObject);
         NSArray *arr4 = responseObject[@"data"];
         for (NSDictionary *dic4 in arr4)
         {
             NSString * nickname;
             NSString * avatar;
             NSString * user_id;

             if (![dic4[@"nickname"] isKindOfClass:[NSNull class]])
             {
                 nickname = dic4[@"nickname"];
             }
             if (![dic4[@"avatar"] isKindOfClass:[NSNull class]])
             {
                 avatar = dic4[@"avatar"];
             }
             if (![dic4[@"user_id"] isKindOfClass:[NSNull class]])
             {
                 user_id = dic4[@"user_id"];
             }
             MIDIfoucusmodel * mmact = [MIDIfoucusmodel new];
             mmact.nickname = nickname;
             mmact.avatar = avatar;
             mmact.user_id = user_id;

             [self.focusArr addObject:mmact];
             
         }
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.MyFocustable reloadData];
             
         });
    }
        failure:^(NSError *error)
    {
        NSLog(@"失败");
    }];

    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return self.focusArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString * cellID = @"cell";
    MIDIMyfoucusCell * cell =[tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell)
    {
        cell =[[MIDIMyfoucusCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        cell.backgroundColor =[UIColor colorWithHexString:@"#1B212F"];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

    }
    
    MIDIfoucusmodel * mm1 = self.focusArr[indexPath.row];
    
    
    [cell.heardimgea sd_setImageWithURL:[NSURL URLWithString:mm1.avatar] placeholderImage:nil];
    cell.name.text = mm1.nickname;
    
    
    [cell.foucus setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
    [cell.foucus setTitle:@"已关注" forState:UIControlStateNormal];
    cell.foucus.tag = indexPath.row;
    cell.foucus.selected = YES;
    [cell.foucus addTarget:self action:@selector(Foucus:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kDevice_Is_iPhoneX?HeighX(70):HeightScale(70);
}
- ( UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;
{
    return nil;
}
- ( UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;
{
    return nil;
}
-(void)Foucus:(UIButton * )sender
{
    NSString *typestr = [self.focusArr[sender.tag] user_id];
    
    
    self.followapi = [NSString stringWithFormat:@"%@users/follow?user_id=%@&token=%@",MIDIApiRoot,typestr,_apptoken];
    
    if (sender.selected == YES)
    {
    
        UIAlertController *controller=[UIAlertController alertControllerWithTitle:@"确认不再关注此人？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *act1=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [act1 setValue:[UIColor colorWithHexString:@"#171717"] forKey:@"titleTextColor"];
        
        UIAlertAction *act2=[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [EdHttp get:self.followapi params:nil progress:^(id downloadProgress) {
                
            }
                success:^(id responseObject)
             {
                 NSLog(@"取消成功%@",responseObject);
                 sender.selected=!sender.selected;//每次点击都改变按钮的状态
                 
                 if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
                 {
                     //第一次点击为蓝色（关注）
                     [sender setTitle:@"关注" forState:UIControlStateNormal];
                     [sender setBackgroundColor:[UIColor colorWithHexString:@"#FF005D"]];
                     [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                     [SVProgressHUD showSuccessWithStatus:@"取消成功"];
                     [SVProgressHUD dismissWithDelay:1.0];
                 }
             }
                failure:^(NSError *error)
             {
                 NSLog(@"失败");
             }];

        }];
        [act2 setValue:[UIColor colorWithHexString:@"#FF005D"] forKey:@"titleTextColor"];
        
        [controller addAction:act1];
        [controller addAction:act2];
        [self presentViewController:controller animated:YES completion:^{
            
        }];


    }
    else
    {
        [EdHttp get:self.followapi params:nil progress:^(id downloadProgress)
        {
            
        }
            success:^(id responseObject)
         {
             NSLog(@"取消成功%@",responseObject);
             sender.selected=!sender.selected;//每次点击都改变按钮的状态
             
             if ([[responseObject objectForKey:@"code"] isEqualToNumber:@200])
             {
                 [sender setTitle:@"已关注" forState:UIControlStateNormal];
                 
                 [sender setBackgroundColor:[UIColor colorWithHexString:@"#999999"]];
                 
                 [sender setAccessibilityFrame:CGRectMake(0, 0, WidthScale(100), HeightScale(40))];
                 [SVProgressHUD showSuccessWithStatus:@"关注成功"];
                 [SVProgressHUD dismissWithDelay:1.0];
             }
         }
            failure:^(NSError *error)
         {
             NSLog(@"失败");
         }];
        NSLog(@"取消关注");
    }
}

// 返回上一级
-(void)Block:(UIButton * )sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.translucent = NO;//Bar的模糊效果，默认为YES

    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#171717"];
    self.title = @"我的关注";
      [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"],NSFontAttributeName : [UIFont fontWithName:@"Helvetica-Bold" size:WidthScale(17)]}];
    //    去掉导航黑线
    UIImage *img = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:img  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    [self focusrequest];
    self.focusArr = [NSMutableArray array];
    
    
}
-(void)HomeUI
{
    [self.view addSubview:self.MyFocustable];
}
-(UITableView *)MyFocustable
{
    if (!_MyFocustable)
    {
        _MyFocustable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,kDevice_Is_iPhoneX?HeighX(self.view.frame.size.height - 40):HeightScale(self.view.frame.size.height-40)) style:UITableViewStyleGrouped];
        _MyFocustable.dataSource = self;
        _MyFocustable.delegate = self;
        _MyFocustable.backgroundColor = [UIColor colorWithHexString:@"#1B212F"];
    }
    return _MyFocustable;
}

@end
